var express = require('express');
var app = express();
var bodyParser = require('body-parser')
var session = require('express-session');
var multiparty = require('multiparty');

var path = require('path');
var fs = require("fs");
var mkdirs = require('./libs/mkdirs.js');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", ' 3.2.1')
  // res.header("Content-Type", "application/json;charset=utf-8");
  if (req.method == "OPTIONS") {
    res.send(200);/*让options请求快速返回*/
  } else {
    next();
  }
});

app.use(session({
  // 用来设置在response中范围session id是属性值，reuqest中可以用默认的request.session.id访问。默认值为connect.sid
  name: 'sslogin',
  // 用来注册session id 到cookie中，相当与一个密钥
  secret: 'keyboard cat',
  cookie: {
    path: '/',
    httpOnly: true,
    secure: true,
    maxAge: 60000
  },
  // session存储的实例子
  // store: new FileStore(),
  // 是否允许session重新设置，要保证session有操作的时候必须设置这个属性为true
  resave: true,
  // 是否设置session在存储容器中可以给修改
  saveUninitialized: true,
}))

var sys = JSON.parse(fs.readFileSync("config/sys.json"));
var users = JSON.parse(fs.readFileSync("config/user.json"));
var category = JSON.parse(fs.readFileSync("config/category.json"));
var articles = JSON.parse(fs.readFileSync("config/articles.json"));

function getUUIDFile(suffix) {
  return Date.now() + '.' + suffix;
}

app.post('/login', function (req, res) {
  // 检查参数
  if (req.body.name === undefined || req.body.psw === undefined) {
    res.json({ code: 1, msg: '请输入用户名和密码' });
    return;
  }
  // 用户判断
  var user = users.find(function (item) {
    if (item.name === req.body.name && item.psw === req.body.psw) {
      return item;
    }
  })

  // session
  if (user) {
    req.session.regenerate(function (err) {
      if (err) {
        res.json({ code: 1, msg: '登录失败' + err });
      } else {
        req.session.ssslogin = user.name;
        res.json({ code: 0, msg: '登录成功' });
      }
    })
  } else {
    res.json({ code: 1, msg: '用户名或密码错误' });
  }
});

app.post('/c/imgUpload', function (req, res) {
  var form = new multiparty.Form({ uploadDir: sys.imageDir });
  form.parse(req, function (err, fields, files) {
    mkdirs(sys.imageDir);
    var fileName = getUUIDFile('png');
    if (files.img && files.img.length > 0) {
      // var fileName = files.img[0].path;
      // fileName = fileName.substring(fileName.lastIndexOf(path.sep) + 1, fileName.length);
      // res.send(sys.imageUrl + fileName);
      fs.rename(files.img[0].path, sys.imageDir + fileName, function (err) {
        if (err) {
          res.json({ code: 1, msg: '图片上传失败 ' + err });
        } else {
          res.send(sys.imageUrl + fileName);
        }
      });
    } else if (fields.base64Date && fields.base64Date.length > 0) {
      //将前台传来的base64数据去掉前缀
      var imgData = fields.base64Date[0].replace(/^data:image\/\w+;base64,/, '');
      var dataBuffer = new Buffer(imgData, 'base64');
      //写入文件
      fs.writeFile(sys.imageDir + fileName, dataBuffer, function (err) {
        if (err) {
          res.json({ code: 1, msg: '图片上传失败 ' + err });
        } else {
          res.send(sys.imageUrl + fileName);
        }
      });
    } else {
      res.json({ code: 1, msg: '请图片上传' });
    }
  });
});

app.post('/category/add', function (req, res) {
  if (req.body == undefined || req.body.name == undefined || req.body.name.trim().length == 0) {
    res.json({ code: 1, msg: '分类添加失败' });
    return;
  }

  if (req.body.parent == undefined) {
    req.body.parent = "";
  }

  var c = {
    parent: req.body.parent.trim(),
    name: req.body.name.trim(),
  };

  var cc = category.find(function (item) {
    if (item.name === req.body.name && item.parent === req.body.parent) {
      return item;
    }
  })
  if (cc) {
    res.json({ code: 1, msg: '分类已存在', data: c });
    return;
  }

  category.push(c);
  fs.writeFileSync(sys.categoryPath, JSON.stringify(category, null, 4));
  res.json({ code: 0, msg: '分类添加成功', data: c });
});

app.get('/category/list', function (req, res) {
  res.send(category);
});

app.get('/post/list', function (req, res) {
  res.send(articles);
});

app.post('/post/add', function (req, res) {
  if (req.body.title == undefined) {
    res.json({ code: 1, msg: '请添加标题' });
    return;
  }
  if (req.body.md == undefined || req.body.md.trim().length == 0) {
    res.json({ code: 1, msg: '请添加文章内容' });
    return;
  }

  var category = "";
  if (req.body.category && req.body.category.trim().length > 0) {
    category = req.body.category
  }

  var labels = [];
  if (req.body.labels) {
    try {
      labels = req.body.labels;
    } catch (err) {
    }
  }

  mkdirs(sys.mdDir);
  var fileName;
  if (req.body.fileName && req.body.fileName.trim().length > 0) {
    fileName = req.body.fileName
  } else {
    fileName = getUUIDFile("md")
  }

  fs.writeFileSync(sys.mdDir + fileName, req.body.md);

  var article = articles.find(function (item) {
    if (item.fileName === fileName) {
      return item;
    }
  })

  if (article) {
    article.modifyTime = Date.now();
    article.category = category;
    article.labels = labels;
  } else {
    var currentTime = Date.now();
    article = {
      title: req.body.title.trim(),
      fileName: fileName,
      createTime: currentTime,
      modifyTime: currentTime,
      category: category,
      user: 'admin',// only自己and admin can modify
      labels: labels
    }
    articles.push(article);
  }

  fs.writeFileSync(sys.articlesPath, JSON.stringify(articles, null, 4));

  if (article) {
    res.json({ code: 0, msg: '文章修改成功', data: article });
  } else {
    res.json({ code: 0, msg: '文章保存成功', data: article });
  }
});

// 静态文件
// app.use(express.static(path.join(__dirname, 'blog')));
// app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static('blog'));
app.use(express.static('public'));
// 
// 启动服务
var server = app.listen(8081, function () {
  var host = server.address().address
  var port = server.address().port
  console.log("应用实例，访问地址为 http://%s:%s", host, port)
})